package com.gxar.quick.ar.server.base.controller;

import cn.hutool.core.bean.BeanUtil;
import com.gxar.common.entity.PageResult;
import com.gxar.common.entity.Result;
import com.gxar.common.entity.SystemCodeEnum;
import com.gxar.common.entity.enums.DataScope;
import com.gxar.common.entity.login.LoginUserThread;
import com.gxar.common.entity.login.UserProfile;
import com.gxar.common.exception.APIRuntimeException;
import com.gxar.common.utils.AssertUtils;
import com.gxar.common.utils.StringUtils;
import com.gxar.quick.ar.server.base.common.constant.UserConstant;
import com.gxar.quick.ar.server.base.facade.ShareFacade;
import com.gxar.quick.ar.server.base.model.ResultCodeEnum;
import com.gxar.quick.ar.server.base.model.exchange.vo.request.AdminExchangeItemCreateRequest;
import com.gxar.quick.ar.server.base.model.exchange.vo.request.AdminExchangeItemPreviewRequest;
import com.gxar.quick.ar.server.base.model.exchange.vo.request.AdminExchangeItemTemplateShelvesRequest;
import com.gxar.quick.ar.server.base.model.exchange.vo.response.*;
import com.gxar.quick.ar.server.base.model.share.vo.request.UnlimitedQRCodeRequest;
import com.gxar.quick.ar.server.base.model.share.vo.response.UnlimitedQRCodeResponse;
import com.gxar.quick.ar.server.base.model.user.vo.UserInfoVO;
import com.gxar.quick.ar.server.db.service.ExchangeItemService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Objects;

/**
 * @author linsy
 * @version 1.0
 * @created 2023/11/8 15:41
 */
@Api(tags = "管理端兑换品接口")
@RestController
@RequestMapping("/admin/api/exchange-item")
@RequiredArgsConstructor
@Slf4j
public class AdminExchangeController {

    private final ExchangeItemService exchangeItemService;

    private final ShareFacade shareFacade;

    @ApiOperation("兑换品管理列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page_num", value = "页码", dataType = "number"),
            @ApiImplicitParam(name = "page_size", value = "页记录数", dataType = "number"),
            @ApiImplicitParam(name = "code", value = "兑换码", dataType = "string"),
            @ApiImplicitParam(name = "name", value = "名称", dataType = "string"),
    })
    @GetMapping("")
    public Result<PageResult<AdminExchangeItemPageResponse>> exchangePageList(@RequestParam(name = "page_num", defaultValue = "1") int pageNum,
                                                                              @RequestParam(name = "page_size", defaultValue = "10") int pageSize,
                                                                              @RequestParam(name = "code", required = false) String code,
                                                                              @RequestParam(name = "name", required = false) String name) {
        UserProfile userProfile = LoginUserThread.get();
        if (Objects.isNull(userProfile)) {
            throw new APIRuntimeException(ResultCodeEnum.USER_NOT_EXIST);
        }
        return exchangeItemService.exchangePageList(userProfile, pageNum, pageSize, code, name);
    }

    @ApiOperation("兑换品详情")
    @GetMapping("/{id}")
    public Result<AdminExchangeItemInfoResponse> exchangeInfo(@PathVariable Long id) {
        UserProfile userProfile = LoginUserThread.get();
        if (Objects.isNull(userProfile)) {
            throw new APIRuntimeException(ResultCodeEnum.USER_NOT_EXIST);
        }
        return exchangeItemService.exchangeInfo(userProfile, id);
    }

    @ApiOperation("兑换品创建")
    @PostMapping()
    public Result<AdminExchangeItemCreateResponse> create(HttpServletRequest httpServletRequest, @RequestBody @Valid AdminExchangeItemCreateRequest request) {
        UserProfile userProfile = LoginUserThread.get();
        if (Objects.isNull(userProfile)) {
            throw new APIRuntimeException(ResultCodeEnum.USER_NOT_EXIST);
        }
        AssertUtils.notEmpty(request.getWorksIds(), SystemCodeEnum.PARAMETER_MISSING.getRet(), "请选择模板");
        BigDecimal price = request.getPrice().setScale(2, RoundingMode.HALF_EVEN);
        if (price.compareTo(BigDecimal.ZERO) <= 0) {
            throw new APIRuntimeException(ResultCodeEnum.EXCHANGE_ITEM_PRICE_ERROR);
        }
        String token = httpServletRequest.getHeader(UserConstant.TOKEN_HEADER_NAME);
        String userId = httpServletRequest.getHeader(UserConstant.USER_ID);
        return exchangeItemService.create(userProfile, request, token, userId);
    }

    @ApiOperation("兑换品更新")
    @PutMapping("/{id}")
    public Result<AdminExchangeItemUpdateResponse> updateItem(HttpServletRequest httpServletRequest, @PathVariable Long id, @RequestBody @Valid AdminExchangeItemCreateRequest request) {
        UserProfile userProfile = LoginUserThread.get();
        if (Objects.isNull(userProfile)) {
            throw new APIRuntimeException(ResultCodeEnum.USER_NOT_EXIST);
        }
        AssertUtils.notEmpty(request.getWorksIds(), SystemCodeEnum.PARAMETER_MISSING.getRet(), "请选择模板");
        BigDecimal price = request.getPrice().setScale(2, RoundingMode.HALF_EVEN);
        if (price.compareTo(BigDecimal.ZERO) <= 0) {
            throw new APIRuntimeException(ResultCodeEnum.EXCHANGE_ITEM_PRICE_ERROR);
        }
        String token = httpServletRequest.getHeader(UserConstant.TOKEN_HEADER_NAME);
        String userId = httpServletRequest.getHeader(UserConstant.USER_ID);
        return exchangeItemService.updateItem(userProfile, id, request, token, userId);
    }

    @ApiOperation("兑换品删除")
    @DeleteMapping("/{id}")
    public Result<Boolean> deleteItem(@PathVariable Long id) {
        UserProfile userProfile = LoginUserThread.get();
        if (Objects.isNull(userProfile)) {
            throw new APIRuntimeException(ResultCodeEnum.USER_NOT_EXIST);
        }
        exchangeItemService.deleteItem(userProfile, id);
        return Result.success("删除成功", true);
    }

    @ApiOperation("制作者用户列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page_num", value = "页码", dataType = "number"),
            @ApiImplicitParam(name = "page_size", value = "页记录数", dataType = "number"),
    })
    @GetMapping("/users")
    public Result<PageResult<UserInfoVO>> userList(@RequestParam(name = "page_num", defaultValue = "1") int pageNum,
                                                   @RequestParam(name = "page_size", defaultValue = "10") int pageSize) {
        return exchangeItemService.userList(pageNum, pageSize);
    }


    @ApiOperation("兑换品预览")
    @PostMapping("/preview")
    public Result<AdminExchangeItemPreviewResponse> preview(@RequestBody AdminExchangeItemPreviewRequest request) {
        UnlimitedQRCodeRequest unlimitedQRCodeRequest = new UnlimitedQRCodeRequest();
        BeanUtil.copyProperties(request, unlimitedQRCodeRequest);
        UnlimitedQRCodeResponse result = shareFacade.getUnlimitedQRCode(unlimitedQRCodeRequest);
        AdminExchangeItemPreviewResponse response = new AdminExchangeItemPreviewResponse();
        response.setBuffer(result.getBuffer());
        return Result.success(response);
    }

    @ApiOperation("同步云识别")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "start_time", value = "开始时间", dataType = "string"),
            @ApiImplicitParam(name = "end_time", value = "结束时间", dataType = "string"),
            @ApiImplicitParam(name = "user_id", value = "用户ID", dataType = "string"),
    })
    @PostMapping("/sync-cloud-identify")
    public Result<Boolean> syncCloudIdentify(@RequestParam(value = "start_time", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:SS") String startTime,
                                             @RequestParam(value = "end_time", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:SS") String endTime,
                                             @RequestParam(value = "user_id", required = false) Long userId) {
        return exchangeItemService.syncCloudIdentify(startTime, endTime, userId);
    }

}
